﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MultiResolutioning.Structures;

namespace MultiResolutioning.Collections
{
	/// <summary>
	/// Kolekcja reprezentuje posortowana LinkedList.
	/// </summary>
	public class SortedVertexLinkedList : LinkedList<Vertex>
	{
		/// <summary>
		/// Wstawia w sposob binarny.
		/// </summary>
		/// <param name="item">Element.</param>
		public void BinaryInsert(Vertex item)
		{
			int imin = 0;
			int imax = this.Count -1;
			int imid = 0;
			Vertex temp;
			LinkedListNode<Vertex> tempNode;

			while (imax > imin)
			{
				imid = (imax - imin >> 1) + imin;
				temp = this.ElementAt(imid);

				if (temp.simplOperation.Cost < item.simplOperation.Cost)
				{
					imin = imid + 1;
				}
				else if (temp.simplOperation.Cost > item.simplOperation.Cost)
				{
					imax = imid - 1;
				}
				else
				{
					tempNode = this.First;
					for (int i = 0; i < imid; ++i)
					{
						tempNode = tempNode.Next;
					}

					this.AddAfter(tempNode, item);
					return;
				}
			}

			tempNode = this.First;
			for (int i = 0; i < imin; ++i)
			{
				tempNode = tempNode.Next;
			}

			if (tempNode.Value.simplOperation.Cost < item.simplOperation.Cost)
			{
				this.AddAfter(tempNode, item);
			}
			else
			{
				this.AddBefore(tempNode, item);
			}
		}

		/// <summary>
		/// Wstawia element.
		/// </summary>
		/// <param name="item">Element.</param>
		public void Insert(Vertex item)
		{
			LinkedListNode<Vertex> current = this.First;

			if (current == null)
			{
				this.AddFirst(item);
				return;
			}

			while (current != null)
			{
				if (current.Value.simplOperation.Cost < item.simplOperation.Cost)
				{
					current = current.Next;
					continue;
				}
				else
				{
					this.AddBefore(current, item);
					return;
				}
			}
			
			AddLast(item);
		}
	}
	
}
